<template>
    <el-dialog
        v-model="showDialog"
        :title="dialogTitle"
        :draggable="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        @close="handleClose(formItemRef)"
        @opened="handleOpened"
        @closed="handleClosed(formItemRef)"
    >
     <el-form
         :model="formItem"
         ref="formItemRef"
         :rules="formItemRules"
         label-width="120px"
     >
       <el-form-item label="消息标识" prop="notificationKey">
         <el-input v-model="formItem.notificationKey" type="text"/>
       </el-form-item>
       <el-form-item label="消息标题" prop="notificationTitle">
         <el-input v-model="formItem.notificationTitle" type="text"/>
       </el-form-item>
       <el-form-item label="消息内容" prop="notificationContent">
         <el-input v-model="formItem.notificationContent" type="textarea"/>
       </el-form-item>
       <el-form-item label="消息类型" prop="notificationType">
         <common-dict-select v-model="formItem.notificationType" :dict-key="SYSTEM_NOTIFICATION_TYPE"/>
       </el-form-item>
       <el-form-item label="发送渠道" prop="sendWay">
         <common-dict-select v-model="formItem.sendWay" :dict-key="SYSTEM_SEND_WAY" :multiple="true"/>
       </el-form-item>
       <el-form-item label="接收用户" prop="receiveUser">
         <common-user-select v-model="formItem.receiveUser" :multiple="true"/>
       </el-form-item>
       <el-form-item label="接收角色" prop="receiveRole">
         <common-role-select v-model="formItem.receiveRole" :multiple="true"/>
       </el-form-item>
       <el-form-item label="提示方式" prop="tipWay">
         <common-dict-select v-model="formItem.tipWay" :dict-key="SYSTEM_TIP_WAY" :clearable="false" @change="tipWayChange"></common-dict-select>
       </el-form-item>
       <el-form-item label="发送时间" prop="timeRange" v-if="formItem.showTimeRange"
                     :rules="[{required: true, message: '请填写发送时间', trigger: 'blur'}]"
       >
         <el-date-picker
             v-model="formItem.timeRange"
             type="daterange"
             range-separator="至"
             value-format="YYYY-MM-DD"
             start-placeholder="开始日期"
             end-placeholder="结束日期">
         </el-date-picker>
       </el-form-item>

     </el-form>

      <template #footer>
        <el-button type="primary" @click="confirm(formItemRef)" :loading="confirmLoading">确认</el-button>
        <el-button type="danger" @click="handleClose(formItemRef)">取消</el-button>
      </template>

    </el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref, watch} from "vue";
import type {FormInstance, FormRules} from "element-plus";
import CommonDictSelect from "@/components/common/CommonDictSelect.vue";
import {SYSTEM_NOTIFICATION_TYPE, SYSTEM_SEND_WAY, SYSTEM_TIP_WAY} from "@/constants/dict-constants.ts";
import {DIALOG_EDIT} from "@/constants/common-constant.ts";
import {elMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {getOneNotificationItemReq, saveNotificationItemReq} from "@/api/admin/notification.ts";
import {formatObjToStr} from "@/utils/format-utils.ts";
import CommonUserSelect from "@/components/common/CommonUserSelect.vue";
import CommonRoleSelect from "@/components/common/CommonRoleSelect.vue";
import {checkIsNull} from "@/utils/check-utils.ts";

const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  dialogTitle: {
    type: String,
    default: ''
  },
  dialogType: {
    type: String,
    default: ''
  },
  relationId: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['handleClosed', 'handleClose'])
const showDialog = ref(props.showDialog)
watch(() => props.showDialog, (val:boolean) => {
  showDialog.value = val
})

interface FormItem {
  id: string;
  notificationKey: string;
  notificationTitle: string;
  notificationContent: string;
  notificationType: string;
  sendWay: any;
  tipWay: any;
  receiveUser: any;
  receiveRole: any;
  timeRange: any;
  showTimeRange: boolean;
}

const formItem = reactive<FormItem>({
  id: '',
  notificationKey: '',
  notificationTitle: '',
  notificationContent: '',
  notificationType: '',
  sendWay: [],
  tipWay: '',
  receiveUser: [],
  receiveRole: [],
  timeRange: [],
  showTimeRange: false
})

const formItemRef = ref<FormInstance>()

const formItemRules = reactive<FormRules<FormItem>>({
  notificationKey: [
    {required: true, message: '请输入消息标识', trigger: 'blur'},
  ],
  notificationTitle: [
    {required: true, message: '请输入消息标题', trigger: 'blur'},
  ],
  notificationContent: [
    {required: true, message: '请输入消息内容', trigger: 'blur'},
  ],
  notificationType: [
    {required: true, message: '请选择消息类型', trigger: 'blur'},
  ],
  sendWay: [
    {required: true, message: '请选择发送渠道', trigger: 'blur'},
  ],
  tipWay: [
      {required: true, message: '请选择提示方式', trigger: 'blur'},
  ]
})

const confirmLoading = ref<boolean>(false)
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid, fields) => {
    if (!valid){
      warningMessageTip("请填写完整信息")
      return
    } else {
      commonConfirm(formEl).then()
    }
  })
}

const commonConfirm = async (formEl: FormInstance | undefined) => {

  if (checkIsNull(formItem.receiveUser) && checkIsNull(formItem.receiveRole)) {
    warningMessageTip("请选择接收用户或接收角色")
    return;
  }

  confirmLoading.value = true
  const params = {
    id: props.relationId,
    notificationKey: formItem.notificationKey,
    notificationTitle: formItem.notificationTitle,
    notificationContent: formItem.notificationContent,
    notificationType: formItem.notificationType,
    sendWay: formItem.sendWay.join(','),
    planStartTime: formItem.timeRange ? formItem.timeRange[0] : null,
    planEndTime: formItem.timeRange ? formItem.timeRange[1] : null,
    tipWay: formItem.tipWay,
    receiveUser: formItem.receiveUser.join(','),
    receiveRole: formItem.receiveRole.join(',')
  }
  const res: any = await saveNotificationItemReq(params)
  elMessageTip(res.tipType, res.message)
  confirmLoading.value = false
  if (res.code === RESPONSE_CODE_SUCCESS) {
    handleClosed(formEl)
  }
}

const handleClose = (formEl: FormInstance | undefined) => {
  reset(formEl)
  emit('handleClose', false)

}

const handleClosed = (formEl: FormInstance | undefined) => {
  reset(formEl)
  emit('handleClosed', false)
}

const handleOpened = () => {
  if (props.dialogType === DIALOG_EDIT) {
    initFormInfo().then()
  }
}

const initFormInfo = async () => {
  const params = {
    id: props.relationId
  }
  const res: any = await getOneNotificationItemReq(params)
  if (res.code === 200) {
    const data = res.data
    formItem.id = data.id
    formItem.notificationKey = data.notificationKey
    formItem.notificationTitle = data.notificationTitle
    formItem.notificationContent = data.notificationContent
    formItem.notificationType = formatObjToStr(data.notificationType)
    formItem.sendWay = data.sendWay.split(',')
    formItem.timeRange = [data.planStartTime, data.planEndTime]
    formItem.tipWay = formatObjToStr(data.tipWay)
    formItem.receiveUser = data.receiveUser.split(',')
    formItem.receiveRole = data.receiveRole.split(',')
  }
}

const tipWayChange = () => {
  if (formItem.tipWay === '1') {
    formItem.showTimeRange = true
    formItem.timeRange = []
  } else {
    formItem.showTimeRange = false
  }
}

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style scoped>

</style>